package com.ztjava.common.tool.push;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.digest.DigestUtils;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.ztjava.core.Constant;
import com.ztjava.core.tool.ViewTool;

/***
 * 秒嘀科技验证短信接口
 * @author Administrator
 * http://www.miaodiyun.com/
 */
public class SmsMiaoDiAuthImp implements PushInterface{
	private static final String URL = "https://api.miaodiyun.com/20150822/industrySMS/sendSMS";
	private static final String account_sid = "COMMON_PUSH_MIAODI_ACCOUNT_SID";
	private static final String auth_token = "COMMON_PUSH_MIAODI_AUTH_TOKEN";
	
	@Override
	public Ret push(String to,String content){
		String body = "accountSid="+ ViewTool.param(account_sid)  
				+ "&to=" + to 
				+ "&smsContent=" + content
				+ createCommonParam();
		//System.out.println(body);
		// 提交请求
		String result = "";
		try {
			 result = HttpKit.post(URL, body);
		}catch (Exception e){
			e.printStackTrace();
			return Ret.create(Constant.RESULT, Constant.ERROR).set(Constant.MESSAGE, "接口错误！");
		}
		JSONObject json = JSONObject.parseObject(result);
		if(json.getString("respCode").equals("00000")){
			return Ret.create(Constant.RESULT, Constant.SUCCESS).set(Constant.MESSAGE, "发送成功！");
		}else {
			return Ret.create(Constant.RESULT, Constant.ERROR).set(Constant.MESSAGE, "发送失败:"+json.getString("respCode")+"！");
		}
	}
	/**
	 * 构造通用参数timestamp、sig和respDataType
	 * 
	 * @return
	 */
	public static String createCommonParam(){
		// 时间戳
		String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		// 签名
		String sig = DigestUtils.md5Hex(ViewTool.param(account_sid) 
				+ ViewTool.param(auth_token) + timestamp);
		return "&timestamp=" + timestamp + "&sig=" + sig + "&respDataType=json" ;
	}
	
}
